import 'dart:async';

import 'package:animal/constant/index_constant.dart';
import 'package:animal/network/api.dart';
import 'package:animal/ui/login/NWApi.dart';
import 'package:animal/utils/RuleUtils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

class CodeInputController extends GetxController{
  final TextEditingController codeEditingController;
  final TextEditingController phoneEditingController;
  CodeInputController({required this.codeEditingController,required this.phoneEditingController});

  //提示语
  RxString btnName = "发送验证码".obs;

  //初始倒计时时间
  RxInt count = 60.obs;

  //倒计时计时器
  Timer? timer;

  //倒计时计时器
  RxBool isButtonEnable = true.obs;

  //按钮颜色
  var btnColor = const Color(0XFFFFFFFF).obs;

  void buttonClickListen(){
    if(isButtonEnable.value){         //当按钮可点击时
      isButtonEnable.value=false;   //按钮状态标记
      _initTimer();          //返回null按钮禁止点击
    }
  }

  ///倒计时
  void _initTimer(){
    isButtonEnable.value = false;
    timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      count--;
      if(count.value==0){
        timer.cancel();             //倒计时结束取消定时器
        isButtonEnable.value=true;        //按钮可点击
        count.value=60;                   //重置时间
        btnName.value='重新发送';     //重置按钮文本
        btnColor.value = const Color(0XFFFFFFFF);
      }else{
        btnName.value='$count s';  //更新文本内容
        btnColor.value = KColorConstant.iconNextColor;
      }
    });
  }

  @override
  void onClose() {
    timer?.cancel(); //销毁计时器
    timer = null;
    codeEditingController.dispose();
    super.onClose();
  }

  ///发送短信验证码
  void sendSms(){
    if(!phoneEditingController.text.isNotEmpty){
      SmartDialog.showToast("请输入手机号码",alignment: Alignment.center);
      return;
    }
    if(RuleUtils().checkStringRule(RuleType.phone, phoneEditingController.text, null) != null){
      SmartDialog.showToast("手机号码格式不正确，请重新输入",alignment: Alignment.center);
      return;
    }
    var putData = {
      "mobile":phoneEditingController.text.trim(),
      "smsSendType":"loginCode",
    };
    debugPrint(putData.toString());
    HttpManager().post<String>(NWApi.sendSms,queryParameters: putData).listen((value) {

    },onError: (err){
      debugPrint(err.message);
    });
  }
}